package cn.hu.basic.interceptor;

import cn.hu.basic.annotation.PreAuthorize;
import cn.hu.basic.jwt.JwtUtils;
import cn.hu.basic.jwt.Payload;
import cn.hu.basic.jwt.RsaUtils;
import cn.hu.basic.jwt.UserInfo;
import cn.hu.system.mapper.PermissionMapper;
import cn.hu.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class MyInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //从请求头中获取U-TOKEN
        String token = request.getHeader("U-TOKEN");
        //U-TOKEN是否为null 通过token的值去redis中查询
        if(token != null){
            //Object logininfo = redisTemplate.opsForValue().get(token);
            //解密token获取加密的信息
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource("hrm_auth_rsa.pub").getFile());
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            Logininfo logininfo = payload.getUserInfo().getLogininfo();
            //如果有就放行
            if(logininfo != null){
                //主站用户直接放行
                Logininfo lf = (Logininfo)logininfo;
                if(lf.getType() != 1){
                    //获取要访问的方法上是否有PreAuthorize
                    HandlerMethod method = (HandlerMethod)handler;
                    //获取到注解
                    PreAuthorize methodAnnotation = method.getMethodAnnotation(PreAuthorize.class);
                    //如果获取到了
                    if(methodAnnotation != null){
                        //通过logininfo的id去查询他所有permssion的sn
//                        List<String> sns = permissionMapper.loadPermissionByLoginInfoId(lf.getId());
                        List<String> sns = payload.getUserInfo().getPermissions();
                        //比对查出来的sn是否有要校验接口注解上的sn
                        if(!sns.contains(methodAnnotation.value())){
                            //没有返回没有权限
                            response.setCharacterEncoding("utf-8");
                            response.setContentType("application/json;charset=utf-8");
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"code\":401,\"success\":false,\"message\":\"noPermission\"}");
                            writer.flush();
                            writer.close();
                            return false;
                        }
                    }
                }
                //redisTemplate.opsForValue().set(token,(Logininfo)logininfo,30, TimeUnit.MINUTES);
                return true;
            }
        }
        //如果查询没有，要返回ajaxresult响应
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"code\":401,\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        return false;
    }
}
